<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/15 0015
 * Time: 17:31
 */

namespace app\api\service;


use library\Controller;
use library\tools\Data;
use think\App;
use think\Db;

class MobileService extends Controller
{
    /**
     * 绑定手机号
     * @param string $client
     * @param int $mid
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bind($client, $mid)
    {
        if(!in_array($client,['member','cleaner','agent']))
        {
            throw new \think\Exception("client {$client} not found");
        }
        $data = $this->_input([
            'phone' => $this->request->post('phone'),//电话
            'smscode'  => $this->request->post('smscode'),//验证码
        ],[
            'phone' => 'require|mobile',
            'smscode'  =>'require',
        ],[
            'phone.require' => '手机号不能为空！',
            'phone.mobile'  => '手机号格式错误！',
            'smscode.require'  => '验证码不能为空！',
        ]);
        //验证手机验证码
        $cache = cache($cachekey = "send_register_sms_{$data['phone']}");
        if(!isset($cache['captcha']) || $cache['captcha'] != $data['smscode']){
            $this->error('短信验证码错误！');
        }
        //开始绑定
        //查询数据库是否包含手机号数据
        $phone_member = Db::name(ucfirst($client))->where('phone',$data['phone'])->find();
        $res = true;
        if($phone_member){
            if($phone_member['id'] != $mid){
                //合并用户信息
                $member = Db::name(ucfirst($client))->where('id',$mid)->field('openid,nickname,headimg')->find();
                $updateData = [
                    'id' => $phone_member['id'],
                    'openid' => $member['openid'],
                    'nickname' => $member['nickname'],
                    'headimg' => $member['headimg']
                ];
                try{
                    Db::transaction(function() use ($client,$updateData,$mid){
                        Db::name(ucfirst($client))->update($updateData);//修改用户信息
                        Db::name(ucfirst($client))->where('id',$mid)->delete();//删除多余的
                        //删除老的登陆凭证
                        Db::name('AccessTokens')->where([['client','eq',$client],['user_id','eq',$updateData['id']]])->delete();
                        Db::name('RefreshTokens')->where([['client','eq',$client],['user_id','eq',$updateData['id']]])->delete();
                        //更新登陆凭证
                        Db::name('AccessTokens')->where([['client','eq',$client],['user_id','eq',$mid]])->setField('user_id',$updateData['id']);
                        Db::name('RefreshTokens')->where([['client','eq',$client],['user_id','eq',$mid]])->setField('user_id',$updateData['id']);
                    });
                }catch (\think\Exception $e){
                    $this->error('绑定手机号失败，'.$e->getMessage());
                }
            }
        } else {
            if($client == 'agent')
            {
                $this->error('此手机号未注册！');
            }
            $res = Db::name(ucfirst($client))->where('id',$mid)->setField('phone',$data['phone']);
        }
        if($res !== false)
        {
            $this->success('绑定手机号成功！');
        }
        else
            $this->error('绑定手机号失败！');
    }
}